﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.StaticFiles;
using System.Collections.Generic;

namespace Common
{
  public class HttpUseExceptionHandler
  {
    public static void Init(IApplicationBuilder app, List<string> defaultFileNames = null)
    {
      app.UseAuthentication();

      if (defaultFileNames != null)
      {
        app.UseDefaultFiles(new DefaultFilesOptions
        {
          DefaultFileNames = defaultFileNames
        });
      }

      app.UseStaticFiles();

      app.UseStaticFiles(new StaticFileOptions
      {
        ContentTypeProvider = new FileExtensionContentTypeProvider(new Dictionary<string, string>
                {
                    { ".apk","application/vnd.android.package-archive"},
                    { ".nupkg","application/zip"}
                })
      });


      app.UseExceptionHandler(errorApp =>
       {
         errorApp.Run(async context =>
         {
           string str;
           var error = context.Features.Get<IExceptionHandlerFeature>()?.Error;
           var code = context.Response.StatusCode;
           context.Response.StatusCode = 200;

           if (error?.GetType().Name != "IException")
           {

             if (PublicTool.JsonpAction(out var callback))
             {
               context.Response.ContentType = "text/plain";
               var json = await PublicTool.ReturnErrorJsonp("IException系统错误,请联系管理员");
               str = json.Content;
             }
             else
             {
               context.Response.ContentType = "application/json";
               var json = await PublicTool.ReturnError("IException系统错误,请联系管理员");
               str = PublicTool.JsonResultToStr(json);
             }
           }
           else
           {
             if (PublicTool.JsonpAction(out var callback))
             {
               context.Response.ContentType = "text/plain";
               var json = await PublicTool.ReturnErrorJsonp(error.Message);
               str = json.Content;
             }
             else
             {
               var json = await PublicTool.ReturnError(error.Message);
               str = PublicTool.JsonResultToStr(json);
             }
           }
           await context.Response.WriteAsync(str);
         });
       });

      app.UseStatusCodePages(errorApp =>
      {

      });

      app.UseSwagger();
      app.UseSwaggerUI(x =>
      {
        x.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
        x.RoutePrefix = string.Empty;
      });
      app.UseCors("AllowCors");
    }
  }
}
